import { addNum, subNum } from 'shiptools'
import dayjs from 'dayjs'


/**
 * 获取两个时间的时间差，返回对象（相差x天x分x秒）
 * @param {String | Date} startTime 开始时间
 * @param {String | Date} endTime 结束时间
 * @returns {Object}
 */
export function getDuration (startTime, endTime) {
    const diffTime = dayjs(endTime).diff(dayjs(startTime), 'minute')
    let days = Math.floor(diffTime / 60 / 24)
    let hours = Math.floor(diffTime / 60) % 24
    let minutes = diffTime % 60
    return {
        days,
        hours,
        minutes
    }
}


/**
 * 判断开发票是否过期
 * @param {String} departureDateTime 出发时间
 * @param {Number} validityDays 开发票的有效期，单位天
 * @returns {Boolean} 是否过期
 */
export function isInvoiceExpired (departureDateTime, validityDays) {
    const dayDiff = dayjs().diff(dayjs(departureDateTime), 'day') // 当前时间与出发时间的天数差
    return dayDiff > validityDays
}

/**
 * 清洗和处理返回的订单详情数据
 * @param {Any} data 原始的订单详情数据
 * @returns {Any} 处理后的订单详情数据 
 */
export function cleanOrderData (data) {
    const passengerList = data.shipItemPassengers && data.shipItemPassengers.map(item => {
        return {
            name: item.name,
            passengerId: item.passengerId,
            idType: item.certType,
            idCard: item.certNo,
            mobile: item.phoneNumber,
            seatName: item.seatName,
            ticketPrice: item.ticketPrice,
            seatType: item.seatType,
            seatNo: item.seatNo,
            userType: item.userType,
            secondIdType: item.secondCertType,
            secondIdCard: item.secondCertNo,
            returnSeatName: item.returnSeatName,
            returnTicketPrice: item.returnTicketPrice,
            ticketState: item.ticketState, // 0: 没有发起退票
            ticketStateName: item.ticketStateName,
            carryChildInfo: item.carryChildInfo,
            qrCode: item.qrCode,
            returnTicketBarCode: item.returnTicketBarCode,
            ticketNo: item.ticketNo,
            returnTicketNo: item.returnTicketNo,
            returnSeatNo: item.returnSeatNo
        }
    })

    if (data.discountServiceCharge){
        data.lineServiceAmount = addNum(data.lineServiceAmount, data.discountServiceCharge)
    }
    if (data.deductionServiceCharge) {
        data.voucherReduceAmount = addNum(data.voucherReduceAmount, data.deductionServiceCharge)
    }
    let haveInsFlag = false
    // 有保险相关就展示保险提示
    if (data.vehicleInsuranceAmount || data.passengerInsuranceAmount
        || data.changerRefundInsuranceAmount) {
        haveInsFlag = true
    }

    // ServiceOptionType 6为退改险 1为意外险 10旅意险 11为非实名制保险
    if (data.preferredServiceInfo && data.preferredServiceInfo.serviceAmount && data.preferredServiceInfo.serviceOptions.find(function (option) {
        return option.optionType == 6 || option.optionType == 1 || option.optionType == 10 || option.optionType == 11
    })) {
        haveInsFlag = true
    }

    const _orderDetail = {
        orderId: data.orderId,
        serialId: data.serialId,
        lineId: data.lineId,
        orderState: data.orderState,
        orderStateName: data.orderStateName,
        isRoundTrip: data.roundTrip === 1, // 是否往返票，0：不是，1： 是
        isSerialVoyage: data.serialVoyage === 1, // 是否流水般，0：不是，1： 是
        isNonRealName: data.nonRealName === 1, // 0: 实名制，1：非实名制
        serverTime: data.serverTime,
        createTime: data.createTime,
        payBackTime: data.payBackTime,
        contactName: data.contactName,
        contactCertNo: data.contactCertNo,
        mobile: data.contactNo,
        departure: data.departureCity,
        destination: data.arriveCity,
        isHaveCompositeProduct: data.haveCompositeProduct === 1, // 是否是组合产品，0：不是，1： 是
        totalAmount: data.totalAmount,
        totalPrice: data.totalPrice,
        preferredServiceAmount: data.preferredServiceInfo && data.preferredServiceInfo.serviceAmount,
        isFromRevenueOrder: data.fromRevenueOrder === 1, // 是否来自1.5页面，0：不是，1： 是
        valueAddServiceName: data.preferredServiceInfo && data.preferredServiceInfo.serviceName,
        valueAddServiceOptionList: data.preferredServiceInfo && data.preferredServiceInfo.serviceOptions,
        lineServiceAmount: data.lineServiceAmount,
        haveInsFlag: haveInsFlag,
        insuranceAmount: data.passengerInsuranceAmount,
        changerRefundInsuranceAmount: data.changerRefundInsuranceAmount,
        valueAddServiceReduceAmount: data.preferredServiceInfo && data.preferredServiceInfo.reduceAmount,
        speedOutTicket: data.speedOutTicket,
        shipRightsPackageAmount: data.shipRightsPackageAmount,
        discountUnitPrice: 0,
        shipRightsReduceCost: data.shipRightsReduceCost,
        voucherReduceAmount: data.voucherReduceAmount,
        isGroupTicket: data.groupTicket === 1, // 是否是团体票，0：不是，1： 是
        groupTicketPerferentailAmout: data.groupTicketDiscountAmount,
        vehicleInsuranceAmount: data.vehicleInsuranceAmount,
        shipItemVehicle: data.shipItemVehicle || [],
        shipVehicleTotalPrice: 0,
        isChangeOrder: data.changeOrder === 1, // 是否是改签，0：不是，1： 是
        changeOrder: data.changeOrder, // 改签状态：0,1,2
        changeOrderId: data.changeOrderId,
        changeSerialNo: data.changeSerialNo,
        supplierId: data.supplierId,
        qrCode: data.qrCode,
        alternativeCabins: data.alternativeCabins, // 备选舱位
        alternativeVoyages: data.alternativeVoyages, // 备选航线
        reserveTimeSlot: data.reserveTimeSlot, // 备选时段
        allowCancelVirtualReceiptOrder: data.AllowCancelVirtualReceiptOrder === 1, // 是否允许取消收单
        departureInfo: {
            departureDateTime: data.departureTime,
            date: dayjs(data.departureTime).format('YYYY-MM-DD'),
            departureTime: dayjs(data.departureTime).format('HH:mm'),
            departurePort: data.departurePort,
            arrivalDateTime: data.arriveTime,
            arrivalTime: dayjs(data.arriveTime).format('HH:mm'),
            arrivalPort: data.arrivePort,
            shipName: data.shipName,
            seatClass: '',
            duration: ''
        },
        backTripInfo: {
            departureDateTime: data.returnTime,
            date: dayjs(data.returnTime).format('YYYY-MM-DD'),
            departureTime: dayjs(data.returnTime).format('HH:mm'),
            departurePort: data.arrivePort,
            arrivalDateTime: '',
            arrivalPort: data.departurePort,
            shipName: data.shipName,
            seatClass: ''
        },
        departurePort: data.departurePort,
        passengerList,

        changerRefundInsuranceId: data.changerRefundInsuranceId,
        passengerInsuranceId: data.passengerInsuranceId,
        vehicleInsuranceId: data.vehicleInsuranceId,
        preSaleDays: data.preSaleDays,
        totalInsuranceAmount: data.totalInsuranceAmount,
        discountActivityAmount: data.discountActivityAmount,
        qrCodeUsage: data.qrCodeUsage,
        takeTicketInfo: data.takeTicketInfo,
        supplierDiscountAmount: data.supplierDiscountAmount,
        valueAddDIscountAmountName: data.preferredServiceInfo && data.preferredServiceInfo.discountAmtName,
        valueAddDiscountAmount: data.preferredServiceInfo && data.preferredServiceInfo.discountAmt || 0,
    }
    // 成人数量（包括成人、学生、长者）
    const adultCount = passengerList.filter(item => item.userType != 2).length
    if (adultCount > 0) {
        _orderDetail.discountUnitPrice = data.discountActivityAmount / adultCount
    }
    // 获取舱位名称
    if (passengerList && passengerList.length > 0) {
        const seatClass = passengerList[0].seatName
        const returnSeatClass = passengerList[0].returnSeatName
        _orderDetail.departureInfo.seatClass = seatClass
        _orderDetail.backTripInfo.seatClass = returnSeatClass || '-'
    }
    // 获取航线耗时
    if (!_orderDetail.isSerialVoyage) {
        const { days, hours, minutes } = getDuration(data.departureTime, data.arriveTime)
        let durationText = ''
        if (days > 0) {
            durationText += `${days}天`
        }
        durationText += `${hours}小时${minutes}分`
        _orderDetail.departureInfo.duration = durationText
        _orderDetail.departureInfo.daysOfDuration = days
    }
    // 计算车船价格
    if (_orderDetail.shipItemVehicle && _orderDetail.shipItemVehicle.length > 0) {
        _orderDetail.shipVehicleTotalPrice = _orderDetail.shipItemVehicle.reduce((total, currentValue) => {
            return total + parseFloat(currentValue.ticketPrice)
        }, 0)
    }
    // 团体票
    if (_orderDetail.isGroupTicket) {
        _orderDetail.ticketAllPrice = _orderDetail.totalPrice - _orderDetail.shipVehicleTotalPrice + _orderDetail.groupTicketPerferentailAmout
    } else {
        _orderDetail.ticketAllPrice = _orderDetail.totalPrice - _orderDetail.shipVehicleTotalPrice - _orderDetail.lineServiceAmount
    }

    if (_orderDetail.supplierDiscountAmount) {
        _orderDetail.ticketAllPrice = _orderDetail.ticketAllPrice + _orderDetail.supplierDiscountAmount
    }

    // 增值服务名称去掉'+'
    if (_orderDetail.valueAddServiceName) {
        _orderDetail.valueAddServiceName = _orderDetail.valueAddServiceName.replace(/\+/g, '')
    }
    return _orderDetail
}

/**
 * 是否只购买了船票和带车上船
 * @param {Number} totalPrice 总价
 * @param {Number} ticketPrice 票价
 * @returns {Boolean}
 */
const isOnlyTicket = function (totalPrice, ticketPrice) {
    var totalPriceCopy = totalPrice || 0
    var ticketPriceCopy = ticketPrice || 0
    return totalPriceCopy - ticketPriceCopy === 0
}

export function invoiceFactory(result, orderDetail) {
    const {AlreadyInvoiceInfo, UnInvoiceInfo} = result
    
     // 全部订单状态：待支付,已取消,已支付,已出票,出票失败,退款中,已退款,退票中,退票失败,待出票,改签中,改签成功
     const POSITIVE_ORDER_STATUS = ['已支付', '已出票', '改签中', '退票失败', '已退款']
     const NEGATIVE_ORDER_STATUS = ['退款中', '退票中',  '出票失败', '已退款', '已取消', '改签成功']
     const orderStateName = orderDetail.orderStateName
     const departureDateTime = orderDetail.departureInfo.departureDateTime
     const totalAmount = orderDetail.totalAmount
     const totalPrice = orderDetail.totalPrice

     const _isOnlyTicket = isOnlyTicket(totalAmount, totalPrice)
     const ticketIsInvoice = UnInvoiceInfo.length + AlreadyInvoiceInfo.length <= 0 && result.SupplierInfo && result.SupplierInfo.InvocingType === 0
     const showInvoiceBox = UnInvoiceInfo.length + AlreadyInvoiceInfo.length > 0 || ticketIsInvoice

     const _invoices = UnInvoiceInfo.length > 0? UnInvoiceInfo: AlreadyInvoiceInfo
     if(_invoices.length <= 0) {
        return ticketIsInvoice? {
            showInvoiceBox,
            isFromOrder: true,
            invoiceOperateName: '',
            canEdit: false,
            isAllowed: false,
            invoiceAmount: 0,
            notice: '',
            subTitle: '纸质船票本身为报销凭证',
            invoicingInfo: result.InvoicingInfo,
            supplierInfo: result.SupplierInfo,
            InvoicingInfo: result.InvoicingInfo,
            SupplierInfo: result.SupplierInfo,
            invoiceTips
        }: null
     }

     _invoices.forEach(item => item.id = dayjs(item.CreateTime).valueOf())

     _invoices.sort((a, b) => b.id - a.id)
     
    result.InvoicingInfo =_invoices[0]


     let _invoiceDetail = null
     if (!showInvoiceBox) {
         return _invoiceDetail
     }
     const isSupportInvocingOnLine = result.SupplierInfo.InvocingOnLine === 1 // 是否支持在线开发票，1：支持
     const supplierInfo = {
         invocingExpiryDayCount: result.SupplierInfo.InvocingExpiryDayCount,
         invocingType: result.SupplierInfo.InvocingType,
         invocingOnLine: result.SupplierInfo.InvocingOnLine,
         offlineInvoiceType: result.SupplierInfo.OfflineInvoiceType
     }

     const invoicingInfo = {
         invoiceAmount: result.InvoicingInfo.InvoiceAmount,
         invoiceStatus: result.InvoicingInfo.InvoiceStatus,
         invoiceStatusName: '',
         invoiceTitle: result.InvoicingInfo.InvoiceTitle,
         invoiceTaxNo: result.InvoicingInfo.InvoiceTaxNo,
         email: result.InvoicingInfo.Email,
         invoiceAmountDetail: result.InvoicingInfo.InvoiceAmountDetail,
         titleType: result.InvoicingInfo.TitleType
     }
     
    invoicingInfo.invoiceStatus = AlreadyInvoiceInfo.length <= 0? -1: invoicingInfo.invoiceStatus

     let invoiceAmount = (orderStateName == '已出票' || orderStateName == '已退款') ? invoicingInfo.invoiceAmount : totalAmount || 0;
     const isExpired = isInvoiceExpired(departureDateTime, supplierInfo.invocingExpiryDayCount)
     let invoiceOperateName = ''
     let canEdit = false // 能否编辑或再次开发票
     let notice = ''
     let subTitle = ''
     let isSubtitleNeedTel = false // 副标题是否需要显示电话
     let isNoticeNeedTel = false // 公告栏是否需要显示电话
     let isAllowed = true // 当前发票是否可以点击
    //  if([0, 1].indexOf(supplierInfo.invocingType) > -1) {
    //      // 发票金额 = 总价 - 票价 - 车票
    //      invoiceAmount = subNum(totalAmount, totalPrice)
    //  }

     let invoiceTips = ''
    //  supplierInfo.invocingType = 1
    //  invoicingInfo.invoiceStatus = 1
     if (isSupportInvocingOnLine) {
         switch (supplierInfo.invocingType) {
             case 0:
                 if(_isOnlyTicket) {
                     // 船票即发票
                     notice = '纸质船票即为报销凭证，我司不再提供船票报销凭证'
                     if (invoiceAmount === 0 && invoicingInfo.invoiceStatus == -1) {
                         subTitle = '纸质船票本身为报销凭证'
                         notice = ''
                     }
                     if (isExpired && invoicingInfo.invoiceStatus == -1) {
                         subTitle = `发船后${supplierInfo.invocingExpiryDayCount || 0}天内均可开具`
                         notice = '船票行程已过期，不能申请开票'
                     }

                 } 
                //  else {
                     
                //     invoiceTips = '纸质船票本身为报销凭证，我司不再提供。附加产品在此处开具'
                  
                //  }
                 break;
             case 1:
                // 电子发票
                // if (supplierInfo.offlineInvoiceType === 1) {

                // } else if (supplierInfo.offlineInvoiceType === 2) { // 纸质发票
                //     invoiceTypeForShow = 1
                //     if (_isOnlyTicket) {
                //         invoiceTips = '船票由供应商提供纸质发票快递到收票地址（需到付）'
                //         invoiceTypeForShow = 2
                //     } else {
                //         invoiceTips = '船票由供应商提供纸质发票快递到收票地址（需到付），附加产品在此处开具电子发票'
                //         invoiceTypeForShow = 3
                //     }
                 
                // }

                 // 供应商线下开票
                //  notice = '船票金额暂不支持线上开票，请至线下港口开票或联系同程客服 '
                //  isNoticeNeedTel = true
                //  if (invoiceAmount === 0 && invoicingInfo.invoiceStatus == -1) {
                //      subTitle = '请至线下港口开票或联系同程客服 '
                //      isSubtitleNeedTel = true
                //      notice = ''
                //      isNoticeNeedTel = false
                //  }
                //  if (isExpired && invoicingInfo.invoiceStatus == -1) {
                //      subTitle = `发船后${supplierInfo.invocingExpiryDayCount || 0}天内均可开具`
                //      notice = '船票行程已过期，不能申请开票'
                //      isNoticeNeedTel = false
                //  }
                 break;
             case 2:
                 // 供应商线上开票
                 notice = `航班发船后${supplierInfo.invocingExpiryDayCount || 0}天内均可开票`
                 if (isExpired && invoicingInfo.invoiceStatus == -1) {
                     subTitle = `发船后${supplierInfo.invocingExpiryDayCount || 0}天内均可开具`
                     notice = '船票行程已过期，不能申请开票'
                 }
                 break;
             case 3:
                 // 同程开票
                 notice = `航班发船后${supplierInfo.invocingExpiryDayCount || 0}天内均可开票`
                 if (isExpired && invoicingInfo.invoiceStatus == -1) {
                     subTitle = `发船后${supplierInfo.invocingExpiryDayCount || 0}天内均可开具`
                     notice = '船票行程已过期，不能申请开票'
                 }
                 break;
             default:
                 break;
         }

         // 根据发票状态
         switch (invoicingInfo.invoiceStatus) {
             case -1: { // 未申请
                 invoicingInfo.invoiceStatusName = '未申请'
                 // 这里 判断  是  只要有增值服务 并且在指定订单状态内
                 isAllowed = false
                 if (invoiceAmount > 0 && !isExpired && POSITIVE_ORDER_STATUS.includes(orderStateName)) {
                     invoiceOperateName = '开发票'
                     canEdit = true
                     isAllowed = true
                 }
                 if (invoiceAmount === 0) {
                     invoiceOperateName = ''
                 }
                 if (isExpired) {
                     invoiceOperateName = '未申请'
                 }
                 break
             }
             case 0: { // 已经申请
                //  invoicingInfo.invoiceStatusName = '已申请'
                 invoiceOperateName = '已申请'
                 if (POSITIVE_ORDER_STATUS.includes(orderStateName)) {
                     invoiceOperateName = '已申请'
                     canEdit = true
                 }
                //  if (NEGATIVE_ORDER_STATUS.includes(orderStateName)) {
                //      invoiceOperateName = '已申请'
                //  }
                 break
             }
             case 1: { //开票中
                //  invoicingInfo.invoiceStatusName = '开票中'
                 invoiceOperateName = '开票中'
                 break
             }
             case 2: { // 开票失败
                 invoicingInfo.invoiceStatusName = '开票失败'
                 invoiceOperateName = '开票失败'
                 canEdit = false
                 break
             }
             case 3: { // 开票成功
                 invoiceOperateName = '开票成功'
                 break
             }
             default: {
                 break
             }
         }
         _invoiceDetail = {
             showInvoiceBox,
             isFromOrder: true,
             invoiceOperateName,
             canEdit,
             isAllowed,
             invoiceAmount,
             notice,
             subTitle,
             isNoticeNeedTel,
             isSubtitleNeedTel,
             invoicingInfo,
             supplierInfo,
             InvoicingInfo: result.InvoicingInfo,
             SupplierInfo: result.SupplierInfo,
             
             invoiceTips
            //  invoiceTypeForShow
         }
     }

     return _invoiceDetail
}
/**
* 能否退票（船票或者组合产品的票）
* @param {Any} refundRules 退票规则详情
* @returns {Boolean} 能否退票 
*/
export function canRefundTicket (refundRules) {
   if (refundRules) {
       const canShipTicketRefund = refundRules.CanRefund // 船票是否可退
       const canProductTicketRefund = refundRules.TicketCanRefund // 组合产品的票是否可退
       return canShipTicketRefund || canProductTicketRefund
   }
   return false
}